package com.ruoyi.legal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.core.page.Pages;
import com.ruoyi.common.core.page.Query;
import com.ruoyi.common.query.QueryTool;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.legal.domain.Ajtz;
import com.ruoyi.legal.domain.Xjcl;
import com.ruoyi.legal.service.IAjtzService;
import com.ruoyi.legal.service.IXjclService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.legal.mapper.MessageMapper;
import com.ruoyi.legal.domain.Message;
import com.ruoyi.legal.service.IMessageService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 消息提醒Service业务层处理
 * 
 * @author xwj
 * @date 2025-06-06
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private IAjtzService ajtzService;
    @Autowired
    private IXjclService xjclService;

    /**
     * 查询消息提醒
     * 
     * @param id 消息提醒主键
     * @return 消息提醒
     */
    @Override
    public Message selectMessageById(Long id) {
        return messageMapper.selectMessageById(id);
    }

    /**
     * 查询消息提醒列表
     * 
     * @param message 消息提醒
     * @return 消息提醒
     */
    @Override
    public List<Message> selectMessageList(Message message) {
        return messageMapper.selectMessageList(message);
    }

    /**
     * 新增消息提醒
     * 
     * @param message 消息提醒
     * @return 结果
     */
    @Override
    public Message insertMessage(Message message) {

      //  messageMapper.insertMessage(message);
    save(message);
    return message;
    }

    /**
     * 修改消息提醒
     * 
     * @param message 消息提醒
     * @return 结果
     */
    @Override
    public Message updateMessage(Message message) {

      //  messageMapper.updateMessage(message);
        updateById(message);
        return message;
    }

    /**
     * 批量删除消息提醒
     * 
     * @param ids 需要删除的消息提醒主键
     * @return 结果
     */
    @Override
    public int deleteMessageByIds(Long[] ids) {
        return messageMapper.deleteMessageByIds(ids);
    }

    /**
    * 条件删除
    * @param message 消息提醒
    * @return
    */
    @Override
    public int delete(Message message) {
        QueryWrapper<Message> qw = new QueryWrapper<>();
        QueryTool.condition(qw, message);
        return baseMapper.delete(qw);
    }

    /**
     * mp分页
     * @param message 消息提醒
     * @return
     */
    @Override
    public Pages<Message> queryPage(Message message) {
        QueryWrapper<Message> qw = new QueryWrapper<>();
        QueryTool.condition(qw, message);
        IPage<Message> ipage = new Query<Message>().getPage(message);

        IPage<Message> page = this.page(
                ipage,
                qw
        );
        return new Pages<>(page);
    }



    /**
     * 删除消息提醒信息
     * 
     * @param id 消息提醒主键
     * @return 结果
     */
    @Override
    public int deleteMessageById(Long id) {
        return messageMapper.deleteMessageById(id);
    }

    /**
     * 消息生成
     */
    @Override
    @Transactional
    public void messageGenerated() {
        // 案件台账提醒
        this.generAjtzMessage();

        // 虚假材料提醒
        this.generXjclMessage();
    }



    /**
     * 案件台账消息
     */
    private void generAjtzMessage() {
        Ajtz param1 = new Ajtz();
        param1.setCastZt(1); // 超60天未处决（含90/120天的数据）
        List<Ajtz> notJaList = ajtzService.selectAjtzList(param1);
        param1.setCastZt(5); // 二延截止前，未处决
        List<Ajtz> eyjzList = ajtzService.selectAjtzList(param1);

        Message messageParam = new Message();
        messageParam.setType("1");
        List<Message> messageList = messageMapper.selectMessageList(messageParam);

        List<Long> exitsIds = messageList.stream()
                .map(Message::getRelativeId)
                .collect(Collectors.toList());

        List<Message> insertList = new ArrayList<>();

        Date now = DateUtils.getNowDate();

        notJaList.forEach(aj -> {
            Integer lasjDiff = aj.getLasjDiff();
            String ajmc = aj.getAjmc();
            String ksmc = aj.getKsmc();
            Long ajid = aj.getId();
            Long uid = aj.getCreateId();

//            boolean isExist = exitsIds.contains(aj.getId());
//            if(isExist) {
//               return;
//            }

            String day = "60";
            if(lasjDiff >= 120) day = "120";
            else if(lasjDiff >= 90) day = "90";

            boolean isExist = false;
            for(Message message: messageList) {
                Long rid = message.getRelativeId();
                String rkey = message.getRelativeKey();

                if(rid.equals(ajid) && rkey.equals(day)) {
                    isExist = true;
                    break;
                }
            }

            if(isExist) {
                return;
            }



            // 不存在则插入
            String title = "立案超"+day+"未作出处决决定";

            Message message = new Message();
            message.setType("1");
            message.setRelativeId(aj.getId());
            message.setRelativeKey(day);
            message.setTitle("案件台账");
            message.setContent(title + ":" + ksmc + "【" + ajmc + "】");
            message.setCreateTime(now);
            message.setStatus(0);
            message.setUserId(uid);
            message.setUserName(aj.getCreateBy());
            insertList.add(message);
        });

        // 二延截止前两月未作出处理决定
        eyjzList.forEach(aj -> {
            String ajmc = aj.getAjmc();
            String ksmc = aj.getKsmc();
            boolean isExist = exitsIds.contains(aj.getId());
            if(isExist) {
                return;
            }

            Message message = new Message();
            message.setType("1");
            message.setRelativeId(aj.getId());
            message.setRelativeKey(aj.getEyjzsjDiff() + "");
            message.setRelativeName("tb_ajtz");
            message.setTitle("案件台账");
            message.setContent("二延截止前两月未作出处理决定：" + ksmc + "【" + ajmc + "】");
            message.setCreateTime(now);
            message.setStatus(0);
            message.setUserId(aj.getCreateId());
            message.setUserName(aj.getCreateBy());
            insertList.add(message);
        });

        saveBatch(insertList);
    }

    /**
     * 虚假材料
     */
    private void generXjclMessage() {
        Xjcl param = new Xjcl();
        param.setZt(2);
        List<Xjcl> xjclList = xjclService.selectXjclList(param);

        Message messageParam = new Message();
        messageParam.setType("2");
        List<Message> messageList = messageMapper.selectMessageList(messageParam);


        Date now = DateUtils.getNowDate();

        List<Message> insertList = new ArrayList<>();

        xjclList.forEach(xjcl -> {
            int monthDiff = xjcl.getMonthDiff();
            String mc = xjcl.getMc();
            Long xjid = xjcl.getId();


            String month = "2";
            if(monthDiff >= 5) month = "5";
            else if(monthDiff >= 3) month = "3";

            boolean isExist = false;
            for(Message message: messageList) {
                Long rid = message.getRelativeId();
                String rkey = message.getRelativeKey();

                if(rid.equals(xjid) && rkey.equals(month)) {
                    isExist = true;
                    break;
                }
            }

            if(isExist) {
                return;
            }

            // 不存在则插入
            String title = "受理"+month+"月未调查终结";

            Message message = new Message();
            message.setType("2");
            message.setRelativeId(xjcl.getId());
            message.setRelativeKey(month);
            message.setRelativeName("tb_xjcl");
            message.setTitle("虚假材料");
            message.setContent(title + "：【" + mc + "】" );
            message.setCreateTime(now);
            message.setStatus(0);
            message.setUserId(xjcl.getCreateId());
            message.setUserName(xjcl.getCreateBy());
            insertList.add(message);
        });

        saveBatch(insertList);
    }

    @Override
    public int unreadNum(Message message) {
        return messageMapper.unreadNum(message);
    }
}
